<?php

class session
{
	
	public $data = array();
	public $config;
	public $sid;
	
	function __construct($db,$config)
	{
		$this->db = $db;
		$this->config = $config;
	}
	
	function begin($user_id, $user_ip, $page_id, $auto_create = 0, $enable_autologin = 0, $admin = 0)
	{
		
		$cookiename = $this->config['cookie_name'];
		$cookiepath = $this->config['cookie_path'];
		$cookiedomain = $this->config['cookie_domain'];
		$cookiesecure = $this->config['cookie_secure'];
		
		if (isset($_COOKIE[$cookiename . '_sid']))
		{
			$session_id = isset($_COOKIE[$cookiename . '_sid']) ? $_COOKIE[$cookiename . '_sid'] : '';
			//$sessiondata = isset($_COOKIE[$cookiename . '_data']) ? unserialize(stripslashes($_COOKIE[$cookiename . '_data'])) : array();
			$sessiondata = array();
			$sessionmethod = SESSION_METHOD_COOKIE;
		}
		else
		{
			$sessiondata = array();
			$session_id = (isset($_GET['sid'])) ? $_GET['sid'] : '';
			$sessionmethod = SESSION_METHOD_GET;
		}
		
		//
		if (! preg_match('/^[A-Za-z0-9]*$/', $session_id))
		{
			$session_id = '';
		}
		
		$page_id = (int) $page_id;
		
		$last_visit = 0;
		$current_time = $this->config['time'];
		
		//
		// Are auto-logins allowed?
		// If allow_autologin is not set or is true then they are
		// (same behaviour as old 2.0.x session code)
		//
		if (isset($this->config['allow_autologin']) && ! $this->config['allow_autologin'])
		{
			$enable_autologin = $sessiondata['autologinid'] = false;
		}
		
		// 
		// First off attempt to join with the autologin value if we have one
		// If not, just use the user_id value
		//
		$this->data = array();
		
		if ($user_id != ANONYMOUS)
		{
			if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '' && $user_id)
			{
				$sql = "SELECT SQL_CACHE u.* FROM " . USERS_TABLE . " u, " . SESSIONS_KEYS_TABLE . " k WHERE u.user_id = " . (int) $user_id . " AND u.user_active = 1 AND k.user_id = u.user_id AND k.key_id = '" . md5($sessiondata['autologinid']) . "'";
				if (! ($result = $this->db->sql_query($sql)))
				{
					//message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
				}
				
				$this->data = $this->db->sql_fetchrow($result);
				$this->db->sql_freeresult($result);
				
				$enable_autologin = $login = 1;
			}
			else if (! $auto_create)
			{
				$sessiondata['autologinid'] = '';
				$sessiondata['userid'] = $user_id;
				
				$sql = "SELECT SQL_CACHE * FROM " . USERS_TABLE . " WHERE user_id = " . (int) $user_id . " AND user_active = 1";
				
				if (! ($result = $this->db->sql_query($sql)))
				{
					//message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
				}
				
				$this->data = $this->db->sql_fetchrow($result);
				$this->db->sql_freeresult($result);
				
				$login = 1;
			}
		}
		
		//
		// At this point either $userdata should be populated or
		// one of the below is true
		// * Key didn't match one in the DB
		// * User does not exist
		// * User is inactive
		//
		if (! sizeof($this->data) || ! is_array($this->data) || ! $this->data)
		{
			$sessiondata['autologinid'] = '';
			$sessiondata['userid'] = $user_id = ANONYMOUS;
			$enable_autologin = $login = 0;
			
			$sql = "SELECT SQL_CACHE * FROM " . USERS_TABLE . " WHERE user_id = " . (int) $user_id;
			
			if (! ($result = $this->db->sql_query($sql)))
			{
				//message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
			}
			
			$this->data = $this->db->sql_fetchrow($result);
			
			$this->db->sql_freeresult($result);
		}
		
		$admin = ($this->data['user_level'] == ADMIN) ? 1 : 0;
		
		//
		// Create or update the session
		//
		$sql = "UPDATE " . SESSIONS_TABLE . " SET session_user_id = $user_id, session_start = $current_time, session_time = $current_time, session_page = $page_id, session_logged_in = $login, session_admin = $admin WHERE session_id = '" . $session_id . "' AND session_ip = '$user_ip'";
		
		if (! $this->db->sql_query($sql) || ! $this->db->sql_affectedrows())
		{
			$session_id = md5(rand());
			
			$sql = "INSERT INTO " . SESSIONS_TABLE . " (session_id, session_user_id, session_start, session_time, session_ip, session_page, session_logged_in, session_admin) VALUES ('$session_id', $user_id, $current_time, $current_time, '$user_ip', $page_id, $login, $admin)";
			
			if (! $this->db->sql_query($sql))
			{
				//message_die(CRITICAL_ERROR, 'Error creating new session', '', __LINE__, __FILE__, $sql);
			}
		}
		
		if ($user_id != ANONYMOUS)
		{
			$last_visit = ($this->data['user_session_time'] > 0) ? $this->data['user_session_time'] : $current_time;
			
			if (! $admin)
			{
				$sql = "UPDATE " . USERS_TABLE . " SET user_session_time = $current_time, user_session_page = $page_id, user_lastvisit = $last_visit WHERE user_id = $user_id";
				if (! $this->db->sql_query($sql))
				{
					//message_die(CRITICAL_ERROR, 'Error updating last visit time', '', __LINE__, __FILE__, $sql);
				}
			}
			
			$this->data['user_lastvisit'] = $last_visit;
			
			//
			// Regenerate the auto-login key
			//
			if ($enable_autologin)
			{
				$auto_login_key = rand() . rand();
				
				if (isset($sessiondata['autologinid']) && (string) $sessiondata['autologinid'] != '')
				{
					$sql = "UPDATE " . SESSIONS_KEYS_TABLE . " SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time WHERE key_id = '" . md5($sessiondata['autologinid']) . "'";
				}
				else
				{
					$sql = "INSERT INTO " . SESSIONS_KEYS_TABLE . "(key_id, user_id, last_ip, last_login) VALUES ('" . md5($auto_login_key) . "', $user_id, '$user_ip', $current_time)";
				}
				
				if (! $this->db->sql_query($sql))
				{
					//message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
				}
				
				$sessiondata['autologinid'] = $auto_login_key;
				unset($auto_login_key);
			}
			else
			{
				$sessiondata['autologinid'] = '';
			}
			
			//		$sessiondata['autologinid'] = (!$admin) ? (( $enable_autologin && $sessionmethod == SESSION_METHOD_COOKIE ) ? $auto_login_key : '') : $sessiondata['autologinid'];
			$sessiondata['userid'] = $user_id;
		}
		
		$this->data['session_id'] = $session_id;
		$this->data['session_ip'] = $user_ip;
		$this->data['session_user_id'] = $user_id;
		$this->data['session_logged_in'] = $login;
		$this->data['session_page'] = $page_id;
		$this->data['session_start'] = $current_time;
		$this->data['session_time'] = $current_time;
		$this->data['session_admin'] = $admin;
		$this->data['session_key'] = $sessiondata['autologinid'];

		//setcookie($cookiename . '_data', $session_id, $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
		
		setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);

		$this->sid = 'sid=' . $session_id;
	}
	
	//
	// Checks for a given user session, tidies session table and updates user
	// sessions at each page refresh
	//
	function pagestart($user_ip, $thispage_id)
	{
		
		$cookiename = $this->config['cookie_name'];
		$cookiepath = $this->config['cookie_path'];
		$cookiedomain = $this->config['cookie_domain'];
		$cookiesecure = $this->config['cookie_secure'];
		
		$current_time = time();
		unset($this->data);
		
		if (isset($_COOKIE[$cookiename . '_sid']))
		{
			//$sessiondata = isset($_COOKIE[$cookiename . '_data']) ? unserialize(stripslashes($_COOKIE[$cookiename . '_data'])) : array();
			$session_id = isset($_COOKIE[$cookiename . '_sid']) ? $_COOKIE[$cookiename . '_sid'] : '';
			$sessionmethod = SESSION_METHOD_COOKIE;
		}
		else
		{
			$sessiondata = array();
			$session_id = (isset($_GET['sid'])) ? $_GET['sid'] : '';
			$sessionmethod = SESSION_METHOD_GET;
		}
		
		// 
		if (! preg_match('/^[A-Za-z0-9]*$/', $session_id))
		{
			$session_id = '';
		}
		
		$thispage_id = (int) $thispage_id;
		
		//
		// Does a session exist?
		//
		

		if (! empty($session_id))
		{
			//
			// session_id exists so go ahead and attempt to grab all
			// data in preparation
			//
			$sql = "SELECT SQL_CACHE u.*, s.* FROM " . SESSIONS_TABLE . " s, " . USERS_TABLE . " u WHERE s.session_id = '$session_id' AND u.user_id = s.session_user_id";
			
			if (! ($result = $this->db->sql_query($sql)))
			{
				//message_die(CRITICAL_ERROR, 'Error doing DB query userdata row fetch', '', __LINE__, __FILE__, $sql);
			}
			
			$this->data = $this->db->sql_fetchrow($result);
			
			//
			// Did the session exist in the DB?
			//
			if (isset($this->data['user_id']))
			{
				//
				// Do not check IP assuming equivalence, if IPv4 we'll check only first 24
				// bits ... I've been told (by vHiker) this should alleviate problems with 
				// load balanced et al proxies while retaining some reliance on IP security.
				//
				$ip_check_s = substr($this->data['session_ip'], 0, 6);
				$ip_check_u = substr($user_ip, 0, 6);
				
				if ($ip_check_s == $ip_check_u)
				{
					$this->sid = ($sessionmethod == SESSION_METHOD_GET || defined('IN_ADMIN')) ? 'sid=' . $session_id : '';
					
					//
					// Only update session DB a minute or so after last update
					//
					if ($current_time - $this->data['session_time'] > 60)
					{
						// A little trick to reset session_admin on session re-usage
						$update_admin = (! defined('IN_ADMIN') && $current_time - $this->data['session_time'] > ($this->config['session_length'] + 60)) ? ', session_admin = 0' : '';
						
						$sql = "UPDATE " . SESSIONS_TABLE . " SET session_time = $current_time, session_page = $thispage_id$update_admin WHERE session_id = '" . $this->data['session_id'] . "'";
						
						if (! $this->db->sql_query($sql))
						{
							//message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
						}
						
						if ($this->data['user_id'] != ANONYMOUS)
						{
							$sql = "UPDATE " . USERS_TABLE . " SET user_session_time = $current_time, user_session_page = $thispage_id WHERE user_id = " . $this->data['user_id'];
							if (! $this->db->sql_query($sql))
							{
								//message_die(CRITICAL_ERROR, 'Error updating sessions table', '', __LINE__, __FILE__, $sql);
							}
						}
						
						$this->clean($this->data['session_id']);
						
						//setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
						setcookie($cookiename . '_sid', $session_id, 0, $cookiepath, $cookiedomain, $cookiesecure);
					}
					
					// Add the session_key to the userdata array if it is set
					if (isset($sessiondata['autologinid']) && $sessiondata['autologinid'] != '')
					{
						$this->data['session_key'] = $sessiondata['autologinid'];
					}
					
					if ($sessionmethod == SESSION_METHOD_GET)
					{
						output_add_rewrite_var('sid', $this->data['session_id']);
					}
					
					return true;
				
				}
			}
		}
		
		//
		// If we reach here then no (valid) session exists. So we'll create a new one,
		// using the cookie user_id if available to pull basic user prefs.
		//
		$user_id = (isset($sessiondata['userid'])) ? intval($sessiondata['userid']) : ANONYMOUS;
		
		if (! ($this->begin($user_id, $user_ip, $thispage_id, TRUE)))
		{
			//message_die(CRITICAL_ERROR, 'Error creating user session', '', __LINE__, __FILE__, $sql);
		}
		
		if ($sessionmethod == SESSION_METHOD_GET)
		{
			output_add_rewrite_var('sid', $this->data['session_id']);
		}
		
		return true;
	}
	
	/**
	 * Removes expired sessions and auto-login keys from the database
	 */
	
	function clean($session_id)
	{
		
		//
		// Delete expired sessions
		//
		$sql = "DELETE FROM " . SESSIONS_TABLE . " WHERE session_time < " . (time() - (int) $this->config['session_length']) . " AND session_id != '$session_id'";
		if (! $this->db->sql_query($sql))
		{
			//message_die(CRITICAL_ERROR, 'Error clearing sessions table', '', __LINE__, __FILE__, $sql);
		}
		
		//
		// Delete expired auto-login keys
		// If max_autologin_time is not set then keys will never be deleted
		// (same behaviour as old 2.0.x session code)
		//
		if (! empty($this->config['max_autologin_time']) && $this->config['max_autologin_time'] > 0)
		{
			$sql = "DELETE FROM " . SESSIONS_KEYS_TABLE . "  WHERE last_login < " . (time() - (86400 * (int) $this->config['max_autologin_time']));
			$this->db->sql_query($sql);
		}
		
		return true;
	}
	
	/**
	 * Reset all login keys for the specified user
	 * Called on password changes
	 */
	function reset_keys($user_id, $user_ip)
	{
		
		$key_sql = ($user_id == $this->data['user_id'] && ! empty($this->data['session_key'])) ? "AND key_id != '" . md5($this->data['session_key']) . "'" : '';
		
		$sql = "DELETE FROM " . SESSIONS_KEYS_TABLE . " WHERE user_id = '" . (int) $user_id . "' $key_sql";
		
		if (! $this->db->sql_query($sql))
		{
			//message_die(CRITICAL_ERROR, 'Error removing auto-login keys', '', __LINE__, __FILE__, $sql);
		}
		
		$where_sql = "session_user_id = " . (int) $user_id;
		$where_sql .= ($user_id == $this->data['user_id']) ? " AND session_id != '" . $this->data['session_id'] . "'" : '';
		$sql = "DELETE FROM " . SESSIONS_TABLE . " WHERE $where_sql";
		if (! $this->db->sql_query($sql))
		{
			//message_die(CRITICAL_ERROR, 'Error removing user session(s)', '', __LINE__, __FILE__, $sql);
		}
		
		if (! empty($key_sql))
		{
			$auto_login_key = rand() . rand();
			
			$current_time = time();
			
			$sql = "UPDATE " . SESSIONS_KEYS_TABLE . " SET last_ip = '$user_ip', key_id = '" . md5($auto_login_key) . "', last_login = $current_time WHERE key_id = '" . md5($this->data['session_key']) . "'";
			
			if (! $this->db->sql_query($sql))
			{
				//message_die(CRITICAL_ERROR, 'Error updating session key', '', __LINE__, __FILE__, $sql);
			}
			
			// And now rebuild the cookie
			$sessiondata['userid'] = $user_id;
			$sessiondata['autologinid'] = $auto_login_key;
			$cookiename = $this->config['cookie_name'];
			$cookiepath = $this->config['cookie_path'];
			$cookiedomain = $this->config['cookie_domain'];
			$cookiesecure = $this->config['cookie_secure'];
			
			//setcookie($cookiename . '_data', serialize($sessiondata), $current_time + 31536000, $cookiepath, $cookiedomain, $cookiesecure);
			
			$this->data['session_key'] = $auto_login_key;
			unset($sessiondata);
			unset($auto_login_key);
		}
	}
	
	//
	// Append $SID to a url. Borrowed from phplib and modified. This is an
	// extra routine utilised by the session code above and acts as a wrapper
	// around every single URL and form action. If you replace the session
	// code you must include this routine, even if it's empty.
	//
	function sid($url, $non_html_amp = false)
	{
		
		if (! empty($this->sid) && ! preg_match('#sid=#', $url))
		{
			$url .= ((strpos($url, '?') !== false) ? (($non_html_amp) ? '&' : '&amp;') : '?') . $this->sid;
		}
		
		return $url;
	}
	
	/**
	 * Terminates the specified session
	 * It will delete the entry in the sessions table for this session,
	 * remove the corresponding auto-login key and reset the cookies
	 */
	function end($session_id, $user_id)
	{
		
		$cookiename = $this->config['cookie_name'];
		$cookiepath = $this->config['cookie_path'];
		$cookiedomain = $this->config['cookie_domain'];
		$cookiesecure = $this->config['cookie_secure'];
		
		$current_time = $this->config['time'];
		
		if (! preg_match('/^[A-Za-z0-9]*$/', $session_id))
		{
			return;
		}
		
		//
		// Delete existing session
		//
		$sql = "DELETE FROM " . SESSIONS_TABLE . " WHERE session_id = '$session_id' 
			AND session_user_id = $user_id";
		if (! $this->db->sql_query($sql))
		{
			//message_die(CRITICAL_ERROR, 'Error removing user session', '', __LINE__, __FILE__, $sql);
		}
		
		//
		// Remove this auto-login entry (if applicable)
		//
		if (isset($this->data['session_key']) && $this->data['session_key'] != '')
		{
			$autologin_key = md5($this->data['session_key']);
			$sql = "DELETE FROM " . SESSIONS_KEYS_TABLE . " WHERE user_id = " . (int) $user_id . "
				AND key_id = '$autologin_key'";
			if (! $this->db->sql_query($sql))
			{
				//message_die(CRITICAL_ERROR, 'Error removing auto-login key', '', __LINE__, __FILE__, $sql);
			}
		}
		
		//
		// We expect that message_die will be called after this function,
		// but just in case it isn't, reset $userdata to the details for a guest
		//
		$sql = "SELECT SQL_CACHE * FROM " . USERS_TABLE . " WHERE user_id = " . ANONYMOUS;
		if (! ($result = $this->db->sql_query($sql)))
		{
			//message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
		}
		if (! ($this->data = $this->db->sql_fetchrow($result)))
		{
			//message_die(CRITICAL_ERROR, 'Error obtaining user details', '', __LINE__, __FILE__, $sql);
		}
		$this->db->sql_freeresult($result);
		
		//setcookie($cookiename . '_data', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
		setcookie($cookiename . '_sid', '', $current_time - 31536000, $cookiepath, $cookiedomain, $cookiesecure);
		
		return true;
	}

}